/*
 * @Author: duchengdong
 * @Date: 2021-10-12 16:51:56
 * @LastEditors: duchengdong
 * @LastEditTime: 2021-12-28 20:58:44
 * @Description:
 */
import { useState } from "react";
import { useAppDispatch, useAppSelector } from "../hooks";
import { addNewBook, updateBook } from "../store/bookSlice";
import { useParams, useHistory ,withRouter,RouteComponentProps} from "react-router-dom";
import { Input, Button } from "antd";
import { uuid } from "../utils/utils";
import Navbar from "../components/Navbar";

interface propTypes extends RouteComponentProps {
    list: any[] | undefined
};

const AddBook = (props:propTypes) => {
    console.log(props)
    const { id } = useParams<{ id: string }>(); //If user comes from /update-book, we will catch id of that book here.
    const history = useHistory();
    const dispatch = useAppDispatch();
    const book = useAppSelector((state) =>
        state.book.bookList.find((book) => book.id === id)
    ); // Selecting particular book's information to prefill inputs for updating.

    const [title, setTitle] = useState<string | undefined>(book?.title || ""); // We are initializing useStates if book variable has title or author.
    const [author, setAuthor] = useState<string | undefined>(
        book?.author || ""
    );

    const handleOnSubmit = () => {
        if (id) {
            editBook();
            return;
        }
        dispatch(addNewBook({ author, title, id: uuid() }));
        clearInputs();
    };

    const editBook = () => {
        dispatch(updateBook({ author, title, id }));
        clearInputs();
        history.push("/");
    };

    const clearInputs = () => {
        setTitle("");
        setAuthor("");
    };

    return (
        <div>
            <Navbar />
            <div>
                <Input
                    value={title}
                    color="white"
                    placeholder="The Lord of the Rings"
                    onChange={(e) => setTitle(e.currentTarget.value)}
                />
            </div>
            <div>
                <Input
                    value={author}
                    color="white"
                    placeholder="J.R.R Tolkien"
                    onChange={(e) => setAuthor(e.currentTarget.value)}
                />
            </div>
            <Button
                onClick={handleOnSubmit}
            >
                Submit
            </Button>
        </div>
    );
};

export default withRouter(AddBook);
